package com.tju.resource.oauth.controller.tb;

import com.tju.resource.model.TbConsumables;
import com.tju.resource.server.TbConsumablesService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ClientParameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Objects;

@RestController
public class TbConsumablesController {
    private final String prefix = "consumables";

    @Autowired
    TbConsumablesService tbConsumablesService;

    /**
     * 查询耗材
     *
     * @param parameters
     * @return
     */
    @PreAuthorize("hasAuthority('sys:consumables:list')")
    @PostMapping(prefix + "/getList")
    public Result<Object> getList(@RequestBody ClientParameters parameters) {
        return tbConsumablesService.getList(parameters);
    }

    /**
     * 添加耗材
     *
     * @param tbConsumables
     * @return
     */
    @PreAuthorize("hasAuthority('sys:consumables:add')")
    @PostMapping(prefix + "/add")
    public Result<Object> add(@Valid @RequestBody TbConsumables tbConsumables, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        }
        return tbConsumablesService.add(tbConsumables);
    }

    /**
     * 删除耗材
     *
     * @param tbConsumables
     * @return
     */
    @PreAuthorize("hasAuthority('sys:consumables:delete')")
    @PostMapping(prefix + "/del")
    public Result<Object> del(@RequestBody TbConsumables tbConsumables) {
        return tbConsumablesService.del(tbConsumables);
    }

    /**
     * 修改耗材
     *
     * @param tbConsumables
     * @return
     */
    @PreAuthorize("hasAuthority('sys:consumables:edit')")
    @PostMapping(prefix + "/upd")
    public Result<Object> upd(@Valid @RequestBody TbConsumables tbConsumables, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        }
        return tbConsumablesService.upd(tbConsumables);
    }
}
